﻿using System;
using System.Collections.ObjectModel;
using System.Net;
using System.Text;
using System.Windows;
using eLearning.Model;
using eLearning.Util;
using Microsoft.Phone.Controls;
using Newtonsoft.Json;

namespace eLearning.View
{
    public partial class AccountPage : PhoneApplicationPage
    {
        private User user;
        private DosenList dosen;
        private MahasiswaList mahasiswa;
        private ObservableCollection<Angkatan> angkatan;
        public AccountPage()
        {
            InitializeComponent();
            FindUserAccountById();
        }

        private void FindUserAccountById()
        {
            string url = null, json = null;

            user = SavedUser.Instance.User;

            if (user != null && (user.Type == User.UserType.Dosen || user.Type == User.UserType.Admin))
            {
                textBlockAngkatan.Visibility = System.Windows.Visibility.Collapsed;
                listAngkatan.Visibility = System.Windows.Visibility.Collapsed;

                Dosen dsn = new Dosen();
                dsn.Nip = user.IdUser;
                url = Config.Instance.DOSEN_SERVICE_URL() + Config.ACCOUNT_ACTION_KEY;
                json = JsonConvert.SerializeObject(dsn);
            }
            else if (user != null && user.Type == User.UserType.Mahasiswa)
            {
                textBlockAngkatan.Visibility = System.Windows.Visibility.Visible;
                listAngkatan.Visibility = System.Windows.Visibility.Visible;
                ListAngkatan();

                Mahasiswa mhs = new Mahasiswa();
                mhs.Nim = user.IdUser;
                url = Config.Instance.MHS_SERVICE_URL() + Config.ACCOUNT_ACTION_KEY;
                json = JsonConvert.SerializeObject(mhs);
            }

            Uri uri = new Uri(url, UriKind.Absolute);
            WebClient client = new WebClient();

            client.Encoding = Encoding.UTF8;
            client.Headers[HttpRequestHeader.ContentType] = "application/json";
            client.Headers[HttpRequestHeader.ContentLength] = json.Length.ToString();

            client.UploadStringCompleted += new UploadStringCompletedEventHandler(findUserAccount_UploadStringCompleted);
            client.UploadStringAsync(uri, "POST", json);
        }

        private void findUserAccount_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
        {
            try
            {
                if (user != null && user.Type == User.UserType.Dosen)
                {
                    dosen = JsonConvert.DeserializeObject<DosenList>(e.Result);
                    textBlockNim.Text = "NIP";
                    textBoxNim.Text = Utility.nullToEmpty(dosen[0].Nip);
                    textBoxUsername.Text = Utility.nullToEmpty(dosen[0].Username);
                    textBoxNama.Text = Utility.nullToEmpty(dosen[0].Nama);
                    textBoxAlamat.Text = Utility.nullToEmpty(dosen[0].Alamat);
                    textBoxTelepon.Text = Utility.nullToEmpty(dosen[0].Telepon);
                    textBoxEmail.Text = Utility.nullToEmpty(dosen[0].Email);
                }
                else if (user != null && user.Type == User.UserType.Mahasiswa)
                {
                    mahasiswa = JsonConvert.DeserializeObject<MahasiswaList>(e.Result);
                    textBlockNim.Text = "NIM";
                    textBoxNim.Text = Utility.nullToEmpty(mahasiswa[0].Nim);
                    textBoxUsername.Text = Utility.nullToEmpty(mahasiswa[0].Username);
                    textBoxNama.Text = Utility.nullToEmpty(mahasiswa[0].Nama);
                    textBoxAlamat.Text = Utility.nullToEmpty(mahasiswa[0].Alamat);
                    textBoxTelepon.Text = Utility.nullToEmpty(mahasiswa[0].Telepon);
                    textBoxEmail.Text = Utility.nullToEmpty(mahasiswa[0].Email);
                    if (listAngkatan.ItemsSource != null && mahasiswa[0].TahunAngkatan.Id != null)
                        listAngkatan.SelectedItem = mahasiswa[0].TahunAngkatan;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("ERROR : " + ex.Message);
            }
        }

        private void ListAngkatan()
        {
            WebClient webClient = new WebClient();

            string url = Config.Instance.MHS_SERVICE_URL() + Config.ANGKATAN_ACTION_KEY;
            Uri uri = new Uri(url, UriKind.Absolute);
            webClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(listAngkatan_DownloadStringCompleted);
            webClient.AllowReadStreamBuffering = true;
            webClient.DownloadStringAsync(uri);
        }

        private void listAngkatan_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            if (e.Error != null)
                return;

            try
            {
                angkatan = JsonConvert.DeserializeObject<ObservableCollection<Angkatan>>(e.Result);
                listAngkatan.ItemsSource = angkatan;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void ValidateUser(bool validate)
        {
            string json = null, url = null;

            if (user != null && user.Type == User.UserType.Dosen)
            {
                Dosen dos = new Dosen();

                if (validate)
                {
                    dos.Nip = user.IdUser;
                    dos.Username = user.Username;
                    dos.Password = passwordOld.Password;

                    json = JsonConvert.SerializeObject(dos);
                    url = Config.Instance.DOSEN_SERVICE_URL() + Config.LOGIN_ACTION_KEY;

                    ValidateAccount(url, json);
                }
                else
                {
                    dos.Id = user.IdUser;
                    dos.Nip = textBoxNim.Text;
                    dos.Username = textBoxUsername.Text;
                    dos.Password = passwordBoxNew.Password;
                    dos.Nama = textBoxNama.Text;
                    dos.Alamat = textBoxAlamat.Text;
                    dos.Telepon = textBoxTelepon.Text;
                    dos.Email = textBoxEmail.Text;

                    json = JsonConvert.SerializeObject(dos);
                    url = Config.Instance.DOSEN_SERVICE_URL() + Config.UPDATE_ACCOUNT_KEY;

                    UpdateAccount(url, json);
                }
            }
            else if (user != null && user.Type == User.UserType.Mahasiswa)
            {
                Mahasiswa mhs = new Mahasiswa();

                if (validate)
                {
                    mhs.Nim = user.IdUser;
                    mhs.Username = user.Username;
                    mhs.Password = passwordOld.Password;

                    json = JsonConvert.SerializeObject(mhs);
                    url = Config.Instance.MHS_SERVICE_URL() + Config.LOGIN_ACTION_KEY;
                    ValidateAccount(url, json);
                }
                else
                {
                    mhs.Id = user.IdUser;
                    mhs.Nim = textBoxNim.Text;
                    mhs.Username = textBoxUsername.Text;
                    mhs.Password = passwordBoxNew.Password;
                    mhs.Nama = textBoxNama.Text;
                    mhs.Alamat = textBoxAlamat.Text;
                    mhs.Telepon = textBoxTelepon.Text;
                    mhs.Email = textBoxEmail.Text;
                    if(listAngkatan.ItemsSource != null)
                        mhs.TahunAngkatan = (Angkatan)listAngkatan.SelectedItem;

                    json = JsonConvert.SerializeObject(mhs);
                    url = Config.Instance.MHS_SERVICE_URL() + Config.UPDATE_ACCOUNT_KEY;

                    UpdateAccount(url, json);
                }
            }
        }

        private void ValidateAccount(string url, string json)
        {
            //deklarasi akses web service
            Uri uri = new Uri(url, UriKind.Absolute);
            WebClient client = new WebClient();

            //Set header
            client.Encoding = Encoding.UTF8;
            client.Headers[HttpRequestHeader.ContentType] = "application/json";
            client.Headers[HttpRequestHeader.ContentLength] = json.Length.ToString();

            //menangani respon yang diberikan oleh server ketika menjalankan method UploadStringAsync()
            client.UploadStringCompleted += new UploadStringCompletedEventHandler(validate_UploadStringCompleted);
            client.UploadStringAsync(uri, "POST", json);
        }

        //menangkap respon dari server
        private void validate_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
        {
            try
            {
                if (e.Cancelled && e.Error != null)
                    return;

                if (e.Result.Contains("Success"))
                    ValidateUser(false);
                else
                    MessageBox.Show("Your old password is not match!");
            }
            catch (WebException ex)
            {
                MessageBox.Show("ERROR : " + ex.Message);
            }
        }

        private void UpdateAccount(string url, string json)
        {
            Uri uri = new Uri(url, UriKind.Absolute);
            WebClient client = new WebClient();

            client.Encoding = Encoding.UTF8;
            client.Headers[HttpRequestHeader.ContentType] = "application/json";
            client.Headers[HttpRequestHeader.ContentLength] = json.Length.ToString();

            client.UploadStringCompleted += new UploadStringCompletedEventHandler(update_UploadStringCompleted);
            client.UploadStringAsync(uri, "POST", json);
        }

        private void update_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
        {
            try
            {
                if (e.Cancelled && e.Error != null)
                    return;
                if (e.Result.Contains("Success"))
                {
                    MessageBox.Show("Message : " + e.Result + "\nYou will logout now, please login again.");
                    SavedUser.Instance.DestroyUser();
                    Utility.GotoPage(this, "/View/LoginPage.xaml");
                }
            }
            catch (WebException ex)
            {
                MessageBox.Show("ERROR : " + ex.Message);
            }
        }

        private void SaveButton_Click(object sender, EventArgs e)
        {
            if (textBoxNim.Text.Length < 1)
            {
                MessageBox.Show("NIM/NIP can't empty!");
                pivotAccount.SelectedIndex = 0;
                textBoxNim.Focus();
                return;
            }
            if (textBoxUsername.Text.Length < 1)
            {
                MessageBox.Show("Username can't empty!");
                pivotAccount.SelectedIndex = 0;
                textBoxUsername.Focus();
                return;
            }
            if (passwordOld.Password.Length < 1)
            {
                MessageBox.Show("Please type your old password!");
                pivotAccount.SelectedIndex = 0;
                passwordOld.Focus();
                return;
            }
            if (passwordBoxNew.Password.Length < 1)
            {
                MessageBox.Show("Please type your new password!");
                pivotAccount.SelectedIndex = 0;
                passwordBoxNew.Focus();
                return;
            }

            if (MessageBox.Show("Save change?", "", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
            {
                ValidateUser(true);
            }
        }

        private void CancelButton_Click(object sender, EventArgs e)
        {
            NavigationService.GoBack();
        }
    }
}